<?php

namespace app\models;

use app\common\Functions;
use yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use yii\data\Sort;
use yii\helpers\Inflector;
use yii\db\Expression;



class OrderSearch extends Order
{
    public $sub_staff_group;
    public $region_name;
    public $user_name;
    public $customer_name;
    public $cust_source_id;//来源
    public $need_area;//需求面积
    public $create_staff_name;//录入人
    public $floor;
    public $budget;
    public $whole_flag;
    public $early_time;

    public static function tableName()
    {
        return Order::tableName();
    }

    public function rules()
    {
        return [
//            [['region_id'], 'safe'],
//            [['region_name'], 'safe'],
            [['remark'], 'safe'],
            [['user_name'], 'safe'],
            [['state'], 'safe'],
            [['region_name'], 'safe'],
            [['state_info'], 'safe'],
            [['orderTypeName'], 'safe'],
            [['cust_source_id'], 'safe'],
            [['need_area'], 'safe'],
            [['create_staff_name'], 'safe'],
            [['sub_staff_group'], 'safe'],
            [['floor'], 'safe'],
            [['budget'], 'safe'],
            [['object_id'], 'safe'],
            [['staff_id'], 'safe'],
            [['create_staff_id'], 'safe'],
            [['early_time'], 'safe'],
        ];
    }




    /***
     * @name   getValidOrderByCustID 根据客户编码获取对应的有效订单
     * @description
     * @param
     * @return
     * @param $order_id
     * @return mixed
     */
    public function getValidOrderByCustID($cust_id)
    {
        $where  = [];

        $where['a.object_id'] = $cust_id;
        $where['a.state'] = Yii::$app->params['ORDER_STATE_VALID'];

        $query  = Order::find()->alias('a');
        $query->joinWith('dealUsers  AS e');
        $query->joinWith('externalAttrs  AS o');

        $query->where($where);
        $model = $query->one();
        return $model;
    }

    // 获取本月的订单总数
    public function getMonthOrderCount($staff_id=null, $where=null ,$x=null)
    {

//        $whereDate = new Expression("DATE_FORMAT(now(),'%Y-%m')");
//        $whereDateFormat = new Expression("date_format(a.input_time,'%Y-%m')");


        $whereLeft = new Expression($where['whereLeft']);
        $whereRight = new Expression($where['whereRight']);

        $query = Order::find()->alias('a');
        $query->joinWith('users  AS b');// 有表关联,需要在order 中添加对应的函数  Staff表的user_id
        $query->joinWith('custs  AS c');//order里的getCusts方法    cust表的id
        $query->joinWith('prodInsts  AS d');/* 获取房源信息 ProdInst表id*/
        $query->joinWith('dealUsers  AS e');/*Staff表的user_id*/
        $query->joinWith('orderTypes  AS f');/*OrderType表的id*/
        $query->joinWith('parentProdInsts  AS g');/* 获取楼盘信息 ProdInst*/


        if(($this->load(Yii::$app->request->queryParams) )){
            $query->joinWith('regions  AS r');/* 获取地区信息*/

            if ($this->need_area)
            {
                $query->joinWith('externalAttrs2  AS x');/* 获取需求面积信息*/
            }

        }
        if($x==3){
            $query->joinWith('staffs  AS z');
        }




        $query->select(['count(*) as qCount']);


        $query->andFilterWhere([$where['whereMidle'],$whereLeft,$whereRight]);
        if($x==3){
            $query->andFilterWhere(['=','z.staff_group', 2]);
        }else{
            $query->andFilterWhere(['=','b.staff_group', 2]);
        }

        $query->andFilterWhere(['=','a.staff_id', $staff_id]);
        $query->andFilterWhere(['=','a.order_type_id',1]);

        $query->andFilterWhere(['like', 'a.remark', $this->remark]);//备注（模糊查询）
      //  $query->andFilterWhere(['=', 'a.state_info', $this->state_info]);//信息部
        $query->andFilterWhere(['=', 'a.state', $where['whereState']]);//状态


        if ( $this->region_name )
        {
                $query->andFilterWhere(['=', 'r.id', $this->region_name]);//地区
        }

        if ( $this->user_name ||  $this->sub_staff_group)
        {
            $query->andFilterWhere(['like', 'e.staff_name', $this->user_name]);//经办人
            $query->andFilterWhere(['=', 'e.sub_staff_group', $this->sub_staff_group]);//状态
        }

        if ( $this->create_staff_name)
        {
            $query->andFilterWhere(['like', 'b.staff_name', $this->create_staff_name]);//录入人
        }

        if ( $this->need_area )
        {
            $query->andFilterWhere(['=', 'x.attr_spec_id', '11']);
            $query->andFilterWhere(['<=', 'x.content', (int)$this->need_area ])
                ->andFilterWhere(['>=', 'x.content2', (int)$this->need_area]);//需求面积
        }

        $monthOrderCount = $query->one();


        return $monthOrderCount['qCount'];
    }


//    public function search($params, $prod_spec_id=null)
//    {
//      $params是会返回的参数
//    }
    /***
     * @name   search
     * @description
     * @param
     * @return
     * @param $params
     * @param null $user_id             有传入既是限定查哪个员工的订单
     * @param null $state               有传入即限制状态
     * @param null $object_type_id      是客户订单还是产品订单
     * @param null $cust_type_id        客户类型
     * @param null $reason              通过撤单原因作为条件查询
     * @param null $create_user_id      通过创建用户查询
     * @param null $time                通过最近一次的修改时间进行查询
     * @param null $phone               通过电话号码查询
     * @param null $queryWhere          通过指定条件查询-数组 （history_order_resumes 查询历史的履历 state 状态）
     * @return ActiveDataProvider
     */
    public function search($params, $user_id=null, $state=null, $object_type_id=null,$cust_type_id=null,$reason=null, $create_user_id = null ,$time=null,$phone=null, $queryWhere=null)
    {
        $where = [];
        $query = Order::find()->alias('a');
        $query->joinWith('users  AS b');// 有表关联,需要在order 中添加对应的函数  Staff表的user_id
        $query->joinWith('custs  AS c');//order里的getCusts方法    cust表的id
        $query->joinWith('prodInsts  AS d');/* 获取房源信息 ProdInst表id*/
        $query->joinWith('dealUsers  AS e');/*Staff表的user_id*/
        $query->joinWith('orderTypes  AS f');/*OrderType表的id*/
        $query->joinWith('parentProdInsts  AS g');/* 获取楼盘信息 ProdInst*/
       // $query->joinWith('orderResumes  AS l');/* 获取履历表数据看是否有回复动作20012*/
        if(($this->load($params) )){
            $query->joinWith('regions  AS r');/* 获取地区信息*/

            if ($this->need_area)
            {
                $query->joinWith('externalAttrs2  AS x');/* 获取需求面积信息*/
            }

        }

        // 如果查询条件参数存在 检查是查询哪个
        if ($queryWhere)
        {
            // 如果有值，是根据履历查询某人的历史
            if ($queryWhere['history_order_resumes'])
            {
                $query->joinWith('historyOrderResumes  AS y');

                $where['y.staff_id']  = $queryWhere['staff_id'];
                $where['a.state']  = $queryWhere['state'];

                // 增加筛选条件 状态等于成交和作废的订单

            }//如果查询历史数据不限定创建人员
            elseif ($user_id)
            {
                $where['a.staff_id'] = $user_id;//4 客服
            }

            // 小组长
            if ($queryWhere['sub_staff_group'])
            {
                $query->joinWith('staffs  AS z');
                $where['z.sub_staff_group'] = $queryWhere['sub_staff_group'];
            }

            // 主管
            if ($queryWhere['staff_group'])
            {
                $query->joinWith('staffs  AS z');
                $where['z.staff_group'] = $queryWhere['staff_group'];
            }





        }
        else
        {//不是查询历史账单才需要关注人
            // 查询某人创建的所有订单
            if ($user_id)
            {
                $where['a.staff_id'] = $user_id;//4 客服
            }

        }

        // 判断传入的$this->cust_source_id是1级 31 32
//        if ($this->cust_source_id==31 || $this->cust_source_id==32)
//
//            $query->joinWith('custSources  AS y');
//            $where['y.parent_source_id'] = $this->cust_source_id;
//            $where['c.cust_source_id'] = 'y.id';
//        }



        if ($create_user_id)
        {
            $where['a.create_staff_id'] = $create_user_id;   // 创建员工
        }


        if ($reason)
        {

            $where['a.reason'] = $reason;//改撤单原因

        }

        if ($state)
        {

            $where['a.state'] = $state;//状态

        }
        if ($phone)
        {

            $where['a.object_id'] = $phone;//object_id

        }



        if ( $object_type_id)
        {
            $where['a.object_type_id'] =  $object_type_id;//对象类型
        }

        if ( $cust_type_id)
        {
            $where['c.cust_type_id'] =  $cust_type_id;//客户类型
        }



        if ($where)
        {
            if ($time)//时间
            {
                $query->andFilterWhere($where);
                if($queryWhere['ing']){

                    $query->andFilterWhere(['>', 'a.input_time', $time ]);
                }else{
                    $query->andFilterWhere(['>=', 'a.modify_date', $time ]);
                }

            }else{
                $query->where($where);
            }

        }
        if ($queryWhere)
        {
            if ($queryWhere['out_time']) {
                $day=Functions::getWeekend();

                $whereLeft = new Expression("DATE_SUB(now(),INTERVAL 4 +".$day." DAY)");
                $query->andFilterWhere(['<', 'a.modify_date',$whereLeft]);
            }
        }



        $sort = new Sort([
            'attributes' => [
                'modify_date',


            ],
        ]);




        $query->orderBy($sort->orders);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'modify_date' => SORT_DESC,
                ]
            ],
            'pagination' => [
                'pageSize' => 50,
            ],
        ]);



//        $sort = $dataProvider->getSort(); // 获取yii自动生成的排序规则
//        $sort->attributes['region_name'] = [ // 添加用户名的排序规则
//            'asc' => ['b.region_name' => SORT_ASC],
//            'desc' => ['b.region_name' => SORT_DESC],
//        ];
//
//
//        $dataProvider->setSort($sort);
//&& $this->validate()



        if (!($this->load($params) )) {
            return $dataProvider;
        }

        // 也可以使用该方式进行where条件的and指定
        $query->andFilterWhere(['like', 'a.remark', $this->remark]);//备注（模糊查询）

        if($this->cust_source_id==31 || $this->cust_source_id==32 ){//1735//淘办

            $sql  = 'SELECT * FROM  ';
            $sql .= CustSource::tableName();
            $sql .= ' as cs ';
            $sql .=  ' WHERE cs.parent_source_id = :parent_id ';
            $lendedAreas = Yii::$app->db->createCommand($sql)
                ->bindValue(':parent_id',$this->cust_source_id)
                ->query(); // 绑定需要一一对应

            $a=[];
            foreach ($lendedAreas as $k=>$region ){

                array_push($a,$region['id']);
            }

//            Yii::trace("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>");
//            Yii::trace($a);

            $query->andFilterWhere(['in', 'c.cust_source_id', $a ]);
        }
        else{
            $query->andFilterWhere(['=', 'c.cust_source_id', $this->cust_source_id]);//客户来源
        }


//        $query->andFilterWhere(['like', 'd.prod_name', $this->prod_name]);


        $query->andFilterWhere(['=', 'r.id', $this->region_name]);//地区



//        if(empty($this->need_area) ){
//            $a=99999;
//            $b=0;
//        }else{
//            $a=$this->need_area;
//            $b=$this->need_area;
//        }

        if($this->need_area)
        {
            $query->andFilterWhere(['=', 'x.attr_spec_id', '11']);
            $query->andFilterWhere(['<=', 'x.content', (int)$this->need_area ])
                ->andFilterWhere(['>=', 'x.content2', (int)$this->need_area]);//需求面积
        }

        if($this->object_id)
        {
            $query->andFilterWhere(['=', 'c.tel', $this->object_id]);//电话查找
        }


        //$query->andFilterWhere(['=', 'a.state', $this->state]);//状态

        $query->andFilterWhere(['=', 'e.user_id', $this->staff_id]);//经办人
        $query->andFilterWhere(['=', 'b.user_id', $this->create_staff_id]);//录入人
        $query->andFilterWhere(['=', 'a.state_info', $this->state_info]);//信息部


        $query->andFilterWhere(['=', 'e.sub_staff_group', $this->sub_staff_group]);//业务区

        return $dataProvider;


    }


}

?>
